package com.gary.springboot.config;

import com.gary.springboot.component.MyLocalResolver;
import com.gary.springboot.registe.MyServlet;
import com.gary.springboot.registe.MyServletRegistrationBean;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author pengrui
 * @date 2020/11/18 - 16:33
 * Configuration 自动配置注解 使用保留自动配置SpringMvc 并增加自定义配置方式  实现WebMvcConfigurer接口
 *
 */
@Configuration
public class MyMvcConfigurarer implements WebMvcConfigurer {

    //Servlet容器中三大组件的配置 Servlet Filter Listener

    /**
     * 配置Servlet容器
     * Filter Listener 配置方法与Servlet一样
     *
     * Servlet配置步骤
     *  1、定义自己的Servlet ： myServlet
     *  2、定义registration 需要继承 ServletRegistrationBean<MyServlet> 注意括号中的泛型 为自己创建的Servlet
     *  3、在Configuration 配置类中 注入到Spring容器中
     * @return
     */
    @Bean
    public MyServletRegistrationBean myServletRegistrationBean() {
        MyServletRegistrationBean myServletRegistrationBean = new MyServletRegistrationBean(new MyServlet(), "/myServlet");
        return myServletRegistrationBean;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    /**
     *  添加登录拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //registry.addInterceptor(new LoginInterceptor())
        //        .addPathPatterns("/**")
        //        .excludePathPatterns("/", "/index.html","/webjars/**","/static/**", "/user/login", "/asserts/**");
    }

    @Bean
    public LocaleResolver myLocaleResolver() {
        return new MyLocalResolver();
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        //定制嵌入式的Servlet容器相关的规则 lambda 表达式
        return factory -> {
            //将端口号指定为8090
            factory.setPort(8090);
        };
    }
}
